using System;
using System.Collections;
using System.Data;

namespace ODX.Core
{
    internal class RowList : ICollection
    {
        private readonly Hashtable rows;

        internal RowList(Hashtable rows)
        {
            this.rows = rows;
        }

        public IEnumerator GetEnumerator()
        {
            DoRefresh();
            return rows.Values.GetEnumerator();
        }

        public DataRow this[string tableName]
        {
            get
            {
                DoRefresh();
                return (DataRow) rows[tableName];
            }
            set { rows[tableName] = value; }
        }

        public DataRow Any
        {
            get
            {
                foreach (DataRow dr in rows.Values)
                {
                    DoRefresh();
                    return dr;
                }
                throw new OdxException("Ups!!!");
            }
        }

        public DataRow[] All
        {
            get
            {
                DoRefresh();
                return (DataRow[]) new ArrayList(rows.Values).ToArray(typeof (DataRow));
            }
        }

        public void CopyTo(Array array, int index)
        {
            rows.Values.CopyTo(array, index);
        }

        public int Count
        {
            get { return rows.Count; }
        }

        public object SyncRoot
        {
            get { return rows.SyncRoot; }
        }

        public bool IsSynchronized
        {
            get { return rows.IsSynchronized; }
        }

        public void Refresh()
        {
            foreach (DataRow r in rows.Values)
                r.RowError = "refresh";
        }

        private void DoRefresh()
        {
            foreach (DataRow dr in rows.Values)
                if (dr.RowError != null && dr.RowError.Length != 0 )
                    Session.GetSession(dr).RefreshRecord(dr["ID"].ToString(), dr.Table.TableName);
        }
    }
}